//
//  LoginViewController.m
//  TestARC
//
//  Created by 晓泉 吴 on 12-9-22.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "DrugWebViewController.h"
#import "JSON/SBJson.h"
#import "MyExtensions.h"
#import "UserManager.h"

@interface LoginViewController ()

@end

@implementation LoginViewController

@synthesize userTF,passwordTF,loginTip;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title=@"Login";
    [self.passwordTF setSecureTextEntry:YES];
    [self showLoginTip];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.userTF = nil;
    self.passwordTF = nil;
    self.loginTip = nil;
    request = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(IBAction)login:(id)sender
{
    NSString *user = [self.userTF text];
    NSString *password = [self.passwordTF text];
    if (user == nil ||
        [user isEqualToString:@""]||
        password == nil||
        [password isEqualToString:@""]) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"注意"
                                                       message:@"请输入完整的登陆信息"
                                                       delegate:self
                                             cancelButtonTitle:@"确定"
                                             otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    [self showWaitView:nil];
    
    int timestamp = (int)[[NSDate date]timeIntervalSince1970];
    NSString * checksum = [[NSString stringWithFormat:@"%@%d%@yaoxia",user,timestamp,password]md5];
    NSString * URL_LOGIN =[NSString stringWithFormat:@"http://www.yaoxia.com/ajaxServlet?style=edf0dea5e5f48bfd5b3f92211ee537b3&username=%@&password=%@&timestamp=%d&checksum=%@",user,password,timestamp,checksum];
    
    NSURL *url = [NSURL URLWithString:URL_LOGIN];
    request = [ASIHTTPRequest requestWithURL:url];
    [request setCompletionBlock:^{
        
        [self hideWaitView];
        // Use when fetching text data
        NSString *responseString = [request responseString];
        
        NSLog(@"responseString = %@",responseString);
        id json = [responseString JSONValue];
        //NSLog(@"meg = %@",[json objectForKey:@"drugInfo"]);
        if ([[json objectForKey:@"code"]intValue] == 500) {
            UIAlertView * messageAlert = [[UIAlertView alloc]
                                          initWithTitle:@"登陆信息"
                                          message:[NSString stringWithFormat:@"%@",[json objectForKey:@"message"]]
                                          delegate:self
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
            [messageAlert show];

        }
        
        NSString * userDisName = [[[json objectForKey:@"userinfo"]objectAtIndex:0]objectForKey:@"disname"];
        NSString * userName = [[[json objectForKey:@"userinfo"]objectAtIndex:0]objectForKey:@"username"];
        if(userDisName.length > 0)
        {
            //NSLog(@"获得name:%@",userDisName);
            [UserManager getCurrentUser].name = userDisName;
            [UserManager getCurrentUser].userName = userName;
            [self showLoginTip];
            
        }
        
        UIAlertView * messageAlert = [[UIAlertView alloc]
                                        initWithTitle:@"登陆信息"
                                        message:[NSString stringWithFormat:@"%@,欢迎\"%@\"",[json objectForKey:@"message"],[UserManager getCurrentUser].name]
                                        delegate:self
                                        cancelButtonTitle:@"OK"
                                        otherButtonTitles:nil];
        [messageAlert show];
        // Use when fetching binary data
        //NSData *responseData = [request responseData];
    }];
    [request setFailedBlock:^{
        [self hideWaitView];
        
        NSError *error = [request error];
        
        NSLog(@"error = %@",error);
        UIAlertView *alert = [[UIAlertView alloc]
                              initWithTitle:@"无法连接到网络"
                              message:nil
                              delegate:self
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil];
        [alert show];
    }];
    [request startAsynchronous];
}

-(IBAction)goRegister:(id)sender
{
    RegisterViewController *myRegisterController = [[RegisterViewController alloc]initWithNibName:@"RegisterViewController" bundle:nil];
    [self.navigationController pushViewController:myRegisterController animated:YES];
}

-(IBAction)goForgot:(id)sender
{
    DrugWebViewController *webController = [[DrugWebViewController alloc]initWithNibName:@"DrugWebViewController" bundle:nil];
    webController.url = @"http://www.yaoxia.com/forget01.jsp";
    webController.title = @"忘记密码";
    
    [self.navigationController pushViewController:webController animated:YES];
}

-(void)showLoginTip
{
    if ([UserManager getCurrentUser].name.length > 0) {
        self.loginTip.text = [NSString stringWithFormat:@"当前登陆用户为:%@",[UserManager getCurrentUser].name];
        self.title = [UserManager getCurrentUser].name;
    }
    else
    {
        self.loginTip.text = @"请填写登录信息:";
        self.title = @"登陆";
    }
}

-(IBAction)dismissKeyBoard:(id)sender
{
    [self.userTF resignFirstResponder];
    [self.passwordTF resignFirstResponder];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self dismissKeyBoard:nil];
    return TRUE;
}

@end
